'use strict';
import React, { Component } from 'react';
import {
    View,
    Text,
    StyleSheet,
    Image,
    ListView,
    RefreshControl,
    ActivityIndicator,
    TouchableOpacity,
    Dimensions,
    Platform,
    Animated,
    TouchableHighlight,
    AsyncStorage,
    Alert,
    StatusBar,
    PixelRatio,
    ScrollView
} from 'react-native';

import Carousel from 'antd-mobile/lib/carousel';
import Flex from 'antd-mobile/lib/flex';
import SearchBar from 'antd-mobile/lib/search-bar';
import Grid from 'antd-mobile/lib/grid';

import * as ToastUtil from '../utils/ToastUtil';
import {HOST as Url} from '../common/Request';
import xFetch from '../XFetch';

import { connect } from 'react-redux';
import NavTitle from '../component/NavTitle';
import {getAll} from '../action/all';

import Swiper from '../component/Swiper';

import GridView from 'react-native-gridview';

import GoodsDetail from './GoodsDetail';

import XFetch from '../XFetch';

import MyWebView from '../utils/MyWebView';

import SearchPro from './SearchPro';

const itemsPerRow = 2;


//首页页面
class Index extends Component {
    constructor(props){
        super(props);
        this.state={
            gvDataSource:[],
            news:[],
            sliderImage:[],//存放轮播图片
            isRefreshing: false,
            menus:[]
        };
        this._onShowDatail = this._onShowDatail.bind(this);
    }

    componentDidMount() {
        this._onRefresh();
    }

    _onRefresh() {
        //获取登录状态
        this.setState({
            isRefreshing: true
        });

        XFetch(`http://www.weiweigo.com/app/goods.aspx?method=commentGoods&topval=1`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                gvDataSource:data,
                isRefreshing:false
            })
        });
        XFetch(`http://www.weiweigo.com/app/content.aspx?method=news&cid=241&len=2`,{
            method:'GET'
        }).then(data=>{
            let _array = [];
            for(var i =0;i < Math.ceil(data.length/2);i++){
                _array[i] = data.slice(0,2);
            }
            this.setState({
                news:_array
            })
        });
        XFetch(`http://www.weiweigo.com/app/content.aspx?method=getAd&cid=186`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                sliderImage:data
            })
        });
        XFetch(`http://www.weiweigo.com/app/content.aspx?method=news&cid=244&len=10`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                menus:data
            })
        });
    }


    _renderSlider(){
        return this.state.sliderImage.map((ele,index) =>{
          return (
               <TouchableOpacity
                  activeOpacity={1}
                  key={'ios'+index}
                  onPress={this._pressSlider.bind(this,ele)}
                  style={styles.slide}>
                      <Image source={{uri:`http://www.weiweigo.com${ele.imgUrl}`}} resizeMode="stretch" style={{height:120,width:Dimensions.get('window').width,justifyContent:'center',alignItems:'center'}}/>
               </TouchableOpacity>
           );
        });
    }

    _pressSlider(ele){
        this.props.navigator.push({
            component:MyWebView,
            name:'MyWebView',
            params:{
                path:ele.url
            }
        })
    }

    onSearchPress(){
        this.props.navigator.push({
            name:'SearchPro',
            component:SearchPro,
        })
    }

    /*
     * 点击菜单的按钮事件
     * index表示点击个数
     */
    onMenuPress(data){
        //console.log('http://www.weiweigo.com/detail.aspx?id='+data.id);
        if(data.keywords == '所有分类'){
            this.props.getAll(true);
            this.props.change(3);
        }else{
            this.props.navigator.push({
                component:MyWebView,
                name:'MyWebView',
                params:{
                    path:'http://www.weiweigo.com/detail.aspx?id='+data.id
                }
            });
        }
    }

    _onShowDatail(data){
        this.props.navigator.push({
            component: GoodsDetail,
            name: 'GoodsDetail',
            params:{
                id:data.id
            }
        })
    }

    _showAds(data){
        //console.log(data);
        this.props.navigator.push({
            component:MyWebView,
            name:'MyWebView',
            params:{
                path:'http://www.weiweigo.com/detail.aspx?id='+data.id
            }
        });
    }

    _renderNews(data){
        return data.map((ele,index)=>{
            return (
                <Flex
                    justify="center"
                    direction="column"
                    key = {`news${index}`}
                    align="start"
                    style={{height:63}}
                >
                    <View>
                        <View style={{flexDirection:'row',paddingLeft:10}}>
                            <Text style={styles.adTip}>头条精华</Text>
                            <TouchableOpacity
                                onPress={this._showAds.bind(this,ele[0])}
                                style={styles.itemAd}
                            >
                                <Text style={styles.adCont}>{ele[0].title}</Text>
                            </TouchableOpacity>
                        </View>
                        <View style={{flexDirection:'row',paddingLeft:10,marginTop:3}}>
                            <TouchableOpacity
                                onPress={()=>{
                                    this.props.change(5);
                                }}
                            >
                                <Text style={styles.adTip}>我要加盟</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                onPress={this._showAds.bind(this,ele[1])}
                                style={[styles.itemAd,{marginTop:3}]}
                            >
                                <Text style={styles.adCont}>{ele[1].title}</Text>
                            </TouchableOpacity>
                        </View>

                    </View>
                </Flex>
            )
        })
    }

    render(){
      const settings = {
        dots: false,
        autoplay: true,
        infinite: true,
        height:60,
        autoplayTimeout:5,
        selectedIndex: 0,
      };
        const {navigator} = this.props;
        return(
          <View style={styles.container}>
              <View style={styles.searchBarContainer}>
                <Text style={{fontSize:16,marginRight:5}}>微微购</Text>
                <View style={styles.searchInput}>
                    <Image style={styles.searchIcon} source={require('../imgs/icSearch.png')}/>
                    <TouchableOpacity
                        onPress={this.onSearchPress.bind(this)}
                        style={{flex:1,paddingLeft:5,height:32,justifyContent:'center'}}>
                        <Text style={{fontSize:14,color:'#AAA',alignSelf:'flex-start'}}>搜素商品</Text>
                    </TouchableOpacity>
                </View>
              </View>
              <ScrollView
                  showsVerticalScrollIndicator={false}
              >
                  <View style={styles.content}>
                      <View style={{height:120}}>
                          {
                              this.state.sliderImage.length>0?
                                  <Carousel
                                      autoplay={true}
                                      infinite={true}
                                  >
                                      {this._renderSlider()}
                                  </Carousel>:
                                  null
                          }

                      </View>
                      <View style={styles.ad}>
                          {/*
                              this.state.menus.map((dataItem, index)=>{
                                  return(
                                  <Flex
                                      justify={'start'}
                                      direction="column"
                                      align="start"
                                      style={{marginLeft:20,marginTop:10}}
                                      key={`menus${index}`}
                                  >
                                      <TouchableOpacity
                                          onPress={this.onMenuPress.bind(this,dataItem)}
                                          style={{justifyContent:'center',alignItems:'center'}}
                                      >
                                          <Image
                                              source={{uri:`http://www.weiweigo.com${dataItem.imgUrl}`}}
                                              style={{width:42,height:42}}
                                              resizeMode="contain"
                                          />
                                          <Text style={{marginTop:6,fontSize:12}}>{dataItem.keywords}</Text>
                                      </TouchableOpacity>
                                  </Flex>
                                  )
                              })
                          */}
                          <GridView
                              data={this.state.menus}
                              itemsPerRow={5}
                              renderItem={(item, sectionID, rowID, itemIndex, itemID) => {
                              return (
                                <Flex
                                      justify={'center'}
                                      direction="column"
                                      align="center"
                                      style={{marginTop:10}}
                                      key={`menus${itemIndex}`}
                                  >
                                      <TouchableOpacity
                                          onPress={this.onMenuPress.bind(this,item)}
                                          style={{justifyContent:'center',alignItems:'center'}}
                                      >
                                          <Image
                                              source={{uri:`http://www.weiweigo.com${item.imgUrl}`}}
                                              style={{width:42,height:42}}
                                              resizeMode="contain"
                                          />
                                          <Text style={{marginTop:6,fontSize:12}}>{item.keywords}</Text>
                                      </TouchableOpacity>
                                  </Flex>
                              );
                            }}
                          />
                      </View>
                      <View style={styles.adNews}>
                          <View style={styles.adImg}>
                              <Image source={require('../imgs/news.png')} style={styles.news}></Image>
                          </View>
                          <View style={styles.sliderNews}>
                              <Swiper
                                  horizontal={false}
                                  autoplay={true}
                                  autoplayTimeout={5}
                                  showsPagination={false}
                                  height={63}

                              >
                                  {this._renderNews(this.state.news)}
                              </Swiper>
                          </View>
                      </View>

                      <View style={styles.plot}>
                          <Image source={require('../imgs/index_goods_title.jpg')} style={styles.list}></Image>
                          <GridView
                            data={this.state.gvDataSource}
                            itemsPerRow={2}
                            renderItem={(item, sectionID, rowID, itemIndex, itemID) => {
                              return (
                                <Flex
                                  justify="start"
                                  direction="column"
                                  align="start"
                                  style={{flex:1,paddingTop:10,paddingLeft:itemID%2 == 0?10:5,paddingRight:itemID%2 == 0?5:10}}
                                >
                                    <TouchableOpacity
                                      style = {{backgroundColor:'#FFF',padding:5}}
                                      activeOpacity={1}
                                      onPress={() => this._onShowDatail(item)}>
                                          <Image source={{uri:`http://www.weiweigo.com${item.imgUrl}`}} style={{width:Dimensions.get('window').width/2-25,height:160}}/>
                                          <Text numberOfLines={1} style={{marginTop:5,color:'#333',fontSize:16}}>{item.title}</Text>
                                          <Text numberOfLines={1} style={{fontSize:14,color:'#e83828',marginTop:3}}>￥{item.price}</Text>
                                          <View style={{alignItems:'center',flexDirection:'row'}}>
                                            <Image style={{width:10,height:12,marginRight:3}} source={require('../imgs/address.png')}/>
                                            <Text numberOfLines={1} style={{fontSize:12,color:'#888988',flex:1}}>商家地址:{item.addressDetail}</Text>
                                          </View>
                                    </TouchableOpacity>
                                </Flex>
                              );
                            }}
                          />
                      </View>
                  </View>
          </ScrollView>
        </View>
    )
    }
}



const styles = StyleSheet.create({
    container: {
        backgroundColor: '#F5F5F5',
        flex: 1,
    },
    plot:{
        marginTop:10,
        flexDirection:'column',
        borderRightWidth:1/PixelRatio.get(),
        borderColor:'#E8E8E8'
    },
    plotHead:{
        backgroundColor:'#F5F5F5',
        height:44,
        justifyContent:'space-between',
        flexDirection:'row',
        alignItems:'center',
        paddingLeft:10,
        paddingRight:10
    },
    adContent:{
        flexDirection:'column',
        marginLeft:8,
        marginTop:10,
        marginBottom:10,
        borderColor:'#F5F5F5',
        borderRightWidth:1,
        paddingRight:8,
        alignItems:'center'
    },
    searchBarContainer:{
        flexDirection:'row',
        height: Platform.OS === 'ios' ? 64 : 48,
        backgroundColor:'#FBDC3A',
        justifyContent:'center',
        alignItems:'center',
        paddingLeft:15,
        paddingRight:35,
        paddingTop: Platform.OS === 'ios' ? 20 : 0,
    },
    searchInput:{
        flex:1,
        flexDirection:'row',
        alignSelf:'center',
        justifyContent: 'center',
        backgroundColor:'#FFF',
        borderRadius:4,
        paddingLeft:10
    },
    searchIcon:{
        width:16,
        height:16,
        alignSelf:'center',
        justifyContent: 'center',
    },
    searchTextInput:{
        flex:1,
        fontSize:14,
        padding:Platform.OS === 'ios' ? 15 : 0,
        paddingLeft:6,
        color:'black'
    },
    ad:{
      marginTop:10,
      backgroundColor:'#FFF',
      paddingBottom:10
    },
    adNews:{
        borderTopWidth:1/PixelRatio.get(),
        backgroundColor:'#FFF',
        alignItems:'center',
        justifyContent: 'center',
        borderBottomWidth:1/PixelRatio.get(),
        borderColor:'#CCC',
        flexDirection:'row',
        paddingLeft:6,
        marginTop:10
    },
    adImg:{
        paddingLeft:3,
        paddingRight:9,
        borderRightWidth:1/PixelRatio.get(),
        borderColor:'#CCC',
    },
    news:{
        width:44,
        height:40
    },
    sliderNews:{
        flex:1,
        justifyContent:'center',
        alignSelf:'center'
    },
    itemAd:{
      flexDirection:'row',
      paddingLeft:10,
        alignItems:'center',
        justifyContent: 'center',
    },
    adTip:{
        borderWidth:1/PixelRatio.get(),
        borderRadius:2,
        borderColor:'#DC0200',
        padding:3,
        fontSize:12,
        color:'#DC0200'
    },
    adCont:{
        color:'#595757',
        marginLeft:0,
        fontSize:12
    },
    list:{
        width:Dimensions.get('window').width,
        height:50
    }
});

const mapStateToProps = (state) => {
    return {}
}

export default connect(
    mapStateToProps,{
        getAll
    }
)(Index)
